package com.earthea.scaffold.common.config.mybatis;

import cn.hutool.core.date.DatePattern;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.earthea.scaffold.common.util.SecurityUtils;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;

@Component
public class CustomerMetaObjectHandler implements MetaObjectHandler {

    /**
     * 获取当前的 UTC 时间
     */
    private String getCurrentUTCTime() {
        return LocalDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
    }

    /**
     * 当前用户
     */
    private Long getCurrentUser() {
        return SecurityUtils.getLoginUserId();
    }


    @Override
    public void insertFill(MetaObject metaObject) {
        String utcNow = getCurrentUTCTime();
        Long loginUserId = getCurrentUser();
        if (metaObject.hasGetter("createTime")) {
            this.strictInsertFill(metaObject, "createTime", String.class, utcNow);
        }
        if (metaObject.hasGetter("updateTime")) {
            this.strictInsertFill(metaObject, "updateTime", String.class, utcNow);
        }
        if (metaObject.hasGetter("createBy")) {
            this.strictInsertFill(metaObject, "createBy", Long.class, loginUserId);
        }
        if (metaObject.hasGetter("updateBy")) {
            this.strictInsertFill(metaObject, "updateBy", Long.class, loginUserId);
        }
    }

    @Override
    public void updateFill(MetaObject metaObject) {
        String utcNow = getCurrentUTCTime();
        Long loginUserId = getCurrentUser();
        if (metaObject.hasGetter("updateTime")) {
            this.strictInsertFill(metaObject, "updateTime", String.class, utcNow);
        }
        if (metaObject.hasGetter("updateBy")) {
            this.strictInsertFill(metaObject, "updateBy", Long.class, loginUserId);
        }
    }
}
